﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using log4net;

public partial class employeeAction : System.Web.UI.Page
{
    //inject PermissionBLL
    private IPermissionBLL perBLL = Factory<IPermissionBLL>.CreateInstance();

    //inject EmployeeBLL
    private IEmployeeBLL empBLL = Factory<IEmployeeBLL>.CreateInstance();

    //Inject log4net
    private static readonly ILog logger = LogManager.GetLogger(typeof(employeeAction).Name);

    protected void Page_Load(object sender, EventArgs e)
    {
        object empId = this.Context.Items["id"];
        string temp = "";
        //come from employee list page
        if (empId != null)
            temp = empId.ToString();
        Inits(temp);
    }


    /// <summary>
    /// InsertOrUpdate :when press [Them/sua] button
    /// </summary>
    private void InsertOrUpdate()
    {
        Guid employeeId = Guid.Empty;
        if (Session["Employee"] != null)
        {
            Employee emp = (Employee)Session["Employee"];
            employeeId = emp.Id;
        }

        //get id from hidden field
        string id = hdnId.Value;

        //init BO
        Employee emBO = new Employee();
        //set to BO  
        if (!String.IsNullOrEmpty(id))
            emBO.Id = new Guid(id);
        emBO.Code = txtCode.Text;
        emBO.FirstName = txtFirstName.Text;
        emBO.LastName = txtLastName.Text;
        emBO.UserName = txtUser.Text;
        emBO.Password = txtPass.Text;
        emBO.Permission = new Permission(cbxPermission.SelectedValue);
        emBO.Email = txtEmail.Text;
        emBO.Gender = Boolean.Parse(rdoGender.SelectedValue);
        emBO.LastUser = employeeId;

        //birthday
        string birth = txtBirthDay.Text;
        if (!String.IsNullOrEmpty(birth))
            emBO.Birthday = DateTime.ParseExact(birth, Constants.DATE_PATTERN, null);
        else
            emBO.Birthday = DateTime.MinValue;

        emBO.IDCard = txtIDCard.Text;
        emBO.Address = txtAddress.Text;
        emBO.HandPhone = txtHandPhone.Text;
        emBO.Position = cbxPosition.SelectedValue;

        try
        {
            if (empBLL.InsertOrUpdate(emBO))
            {
                Response.Redirect(Constants.EMPLOYEE_SHOW);
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
    }

    /// <summary>
    /// Init page
    /// </summary>
    /// <param name="id"></param>
    private void Inits(string id)
    {

        //load to [Quyền] combobox
        LoadPermission();

        //handle [Xoa][Huy] button
        btnReset.ImageUrl = "images/xoa.gif";
        btnReset.Attributes.Add("onmouseover", "this.src='images/xoa_hover.gif'");
        btnReset.Attributes.Add("onmouseout", "this.src='images/xoa.gif'");
        btnCancel.ImageUrl = "images/huy.gif";
        btnCancel.Attributes.Add("onmouseover", "this.src='images/huy_hover.gif'");
        btnCancel.Attributes.Add("onmouseout", "this.src='images/huy.gif'");

        //Insert
        if (String.IsNullOrEmpty(id))
        {
            //handle [Save] button
            btnSave.ImageUrl = "images/save.gif";
            btnSave.Attributes.Add("onmouseover", "this.src='images/save_hover.gif'");
            btnSave.Attributes.Add("onmouseout", "this.src='images/save.gif'");

            //handle title
            lblTitle.Text = "Thêm nhân viên";
            
            //Generate empCode
            if (!Page.IsPostBack)               
                GetEmpCode();

        }//Update
        else
        {
            //handle [Save] button
            btnSave.ImageUrl = "images/edit.jpg";
            btnSave.Attributes.Add("onmouseover", "this.src='images/edit_hover.jpg'");
            btnSave.Attributes.Add("onmouseout", "this.src='images/edit.jpg'");

            //handle title
            lblTitle.Text = "Chỉnh sửa thông tin nhân viên";

            //invisible pasword and confirm field
            rowPass.Visible = false;
            rowConfirm.Visible = false;

            //disable code and username
            txtUser.ReadOnly = true;
            txtUser.CssClass = "disable width_200";

            //load to controls
            LoadUpdate(new Guid(id));
        }

        //page title
        Page.Title = Constants.TITLE_SYSTEM + Constants.SPACE + Constants.SEPARATE + Constants.SPACE + lblTitle.Text;


        //data to test
        // TestData();
    }

    /// <summary>
    /// GetEmpCode
    /// </summary>
    private void GetEmpCode()
    {
        try
        {
            txtCode.Text =Utils.GetEmpCode(empBLL.GetMaxEmpCode());
        }
        catch (Exception ex)
        {
            
           lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
    }

    /// <summary>
    /// LoadUpdate
    /// </summary>
    /// <param name="id"></param>
    private void LoadUpdate(Guid id)
    {
        Employee empBO = null;
        try
        {
            empBO = empBLL.GetById(id);
        }
        catch (Exception ex)
        {

            lblMsg.Text = ex.Message;
        }
        txtCode.Text = hdnCode.Value = empBO.Code;
        txtFirstName.Text = empBO.FirstName;
        txtLastName.Text = empBO.LastName;
        txtUser.Text = empBO.UserName;
        cbxPermission.SelectedValue = empBO.Permission.PermissionID;
        txtEmail.Text = empBO.Email;
        txtAddress.Text = empBO.Address;
        txtHandPhone.Text = empBO.HandPhone;
        txtIDCard.Text = empBO.IDCard;
        rdoGender.SelectedValue = empBO.Gender.ToString();
        cbxPosition.SelectedValue = empBO.Position;
        if (empBO.Birthday != DateTime.MinValue)
            txtBirthDay.Text = empBO.Birthday.ToString(Constants.DATE_PATTERN);
        //save id to hidden field
        hdnId.Value = id.ToString();
    }

    /// <summary>
    /// LoadPermission use to load data to combobox
    /// </summary>
    private void LoadPermission()
    {
        try
        {
            cbxPermission.DataSource = perBLL.LoadPermission();
            cbxPermission.DataTextField = "Name";
            cbxPermission.DataValueField = "PermissionID";
            cbxPermission.DataBind();
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }

    }


    /// <summary>
    /// Clear form
    /// </summary>
    private void Reset()
    {
        if (string.IsNullOrEmpty(hdnId.Value))
        {
            txtCode.Text = "";
            txtFirstName.Text = "";
            txtLastName.Text = "";
            txtUser.Text = "";
            txtPass.Text = "";
            txtConfirm.Text = "";
            cbxPermission.SelectedIndex = 0;
            txtEmail.Text = "";
            rdoGender.SelectedIndex = 2;
            txtBirthDay.Text = "";
            cbxPosition.SelectedIndex = 0;
        }
        else
            this.Page_Load(null, null);
    }

    private bool CheckCodeExist()
    {
        bool flag = false;
        try
        {
            if (empBLL.CheckIsCodeExist(txtCode.Text))
            {
                lblErrorCode.Visible = true;
                lblErrorCode.Text = "Mã nhân viên này đã sử dụng!";
                txtCode.Focus();
                flag = true;
            }
            else
            {
                lblErrorCode.Visible = false;
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }

        }
        return flag;
    }

    private bool CheckUserExist()
    {
        bool flag = false;
        try
        {
            if (empBLL.CheckUserIsExist(txtUser.Text))
            {
                lblErrorUser.Visible = true;
                txtUser.Focus();
                flag = true;
            }
            else
            {
                lblErrorUser.Visible = false;
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }

        }
        return flag;
    }


    protected void btnReset_Click(object sender, ImageClickEventArgs e)
    {
        Reset();
    }
    protected void btnSave_Click(object sender, ImageClickEventArgs e)
    {
        //insert
        if (string.IsNullOrEmpty(hdnId.Value))
        {
            if (!CheckCodeExist())
                InsertOrUpdate();
        }
        //Update
        else
        {
            //Change code
            if (!txtCode.Text.Trim().Equals(hdnCode.Value))
            {
                if (!CheckCodeExist())
                    InsertOrUpdate();
            }
            //No change code
            else
                InsertOrUpdate();
        }

    }
    protected void txtCode_TextChanged(object sender, EventArgs e)
    {
        //Check length
        if (txtCode.Text.Length < 10)
        {
            lblErrorCode.Text = "Mã nhân viên phải 10 ký tự!";
            lblErrorCode.Visible = true;
            return;
        }
        else
            lblErrorCode.Visible = false;

        // System.Threading.Thread.Sleep(1000);
        UpnCode.Update();
        //Insert
        if (string.IsNullOrEmpty(hdnId.Value))
        {
            CheckCodeExist();
        }
        else//update
        {
            if (!txtCode.Text.Trim().Equals(hdnCode.Value))
            {
                CheckCodeExist();
            }
            else
                lblErrorCode.Visible = false;
        }

    }

    protected void txtUser_TextChanged(object sender, EventArgs e)
    {
        upnUser.Update();
        CheckUserExist();
    }
    protected void btnCancel_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect(Constants.EMPLOYEE_SHOW);
    }
}